package org.noisyteam.fxplaylistgrabber.controller;

import org.noisyteam.fxplaylistgrabber.service.PlaylistProviderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.List;

/**
 * Handles requests for the application home page.
 *
 * @author Roman Romanchuk (fatroom@gmail.com)
 */
@Controller
public class PlaylistController {
    private static final Logger logger = LoggerFactory.getLogger(PlaylistController.class);

    private static final String DEFAULT_VIEW = "WEB-INF/views/home.jsp";

    @Autowired
    private PlaylistProviderService provider;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home() {
        logger.trace("Passing through...");
        return DEFAULT_VIEW;
    }

    @RequestMapping(value = "/playlist", method = RequestMethod.GET)
    @ResponseBody
    public List<String> getPlaylist() {
        logger.trace("Fetching last played tracks");
        return provider.getPlaylist();
    }

    @RequestMapping(value = "/refresh", method = RequestMethod.GET)
    @ResponseBody
    public String refresh() throws IOException {
        logger.trace("Refreshing playlist");
        provider.refresh();
        List<String> pl = provider.getPlaylist();
        if (pl.size() > 0)  {
            return provider.getPlaylist().get(0);
        } else {
            return "";
        }
    }
}
